package com.xiehua.task.job;

import com.xiehua.task.job.miscellaneous.EmailMemorandum;
import com.xiehua.task.job.pool.DelayJobPool;
import com.xiehua.task.monitor.Statistics;
import com.xiehua.task.monitor.dingding.Robot;
import com.xiehua.task.monitor.email.Email;
import com.xiehua.task.prop.XiehuaConfig;
import com.xiehua.task.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;

import javax.mail.MessagingException;
import java.time.LocalDateTime;
import java.util.Map;

import static com.xiehua.task.monitor.Statistics.EMAIL_TYPE_EXCETPION;
import static com.xiehua.task.prop.XiehuaConfig.SERVER_EMAIL_DO_NOT_DISTURB;
import static com.xiehua.task.prop.XiehuaConfig.SERVER_MONITOR_SWITCH;

public class PostOffice extends RidesOperationDefualt {

    private static final Logger logger = LoggerFactory.getLogger(PostOffice.class);

    private EmailMemorandum memorandum;

    public PostOffice(Jedis jedis) {
        super(jedis);
        this.memorandum = new EmailMemorandum(jedis);
    }

    /***
     * 写入一个邮件发送标志位
     * **/
    public void writeFlagEmailCount(){
        memorandum.writeFlagEmailCount();
    }

    /***
     * 读取一个邮件发送标志位
     * **/
    public boolean existFlagEmalCount(){
        return memorandum.existFlagEmalCount();
    }

    /**
     * 主题监控开关
     * **/
    public void topicMonitorSwitch(String topic,Boolean flag){
        memorandum.topicMonitorSwitch(topic,flag);
    }

    /**
     * 查询主题监控开关
     * **/
    public Boolean queryTopicMonitorSwitch(String topic){
        return memorandum.queryTopicMonitorSwitch(topic);
    }

    /**
     * 投递邮件
     * **/
    public void delivery(Statistics statistics) throws MessagingException {
        if(logger.isDebugEnabled()) logger.debug("发送邮件咯:{}",statistics);
        Map<String,String> configMap = XiehuaConfig.getInstance();
        if(!Boolean.parseBoolean(configMap.get(SERVER_MONITOR_SWITCH))) return ;//全局开关
        if(!StringUtils.isEmpty(statistics.getTopic()) && !queryTopicMonitorSwitch(statistics.getTopic())) return;//主题开关
        LocalDateTime now = LocalDateTime.now();
        if(EMAIL_TYPE_EXCETPION.equals(statistics.getType()) && Boolean.parseBoolean(configMap.get(SERVER_EMAIL_DO_NOT_DISTURB)) && (now.getHour() >= 21 || now.getHour() <= 7)) return ;//免打扰
        if(EMAIL_TYPE_EXCETPION.equals(statistics.getType()) && !StringUtils.isEmpty(statistics.getTopic()) && memorandum.checkSendEmailRate(statistics.getTopic()) ) return ;//发送频率检查
        if(EMAIL_TYPE_EXCETPION.equals(statistics.getType()) && !StringUtils.isEmpty(statistics.getTopic())) memorandum.sendEmail(statistics.getTopic());//记录本次邮件发送时间
        //发送邮件
        //new Email().sendEmail(statistics);
        //发送钉钉
        new Robot().talk(statistics);
    }
}
